"""
通用处理器
"""
from typing import Any
import imagehash
import io
from PIL import Image
import re
from datetime import datetime
from dateutil import parser
from oss.oss_utils import upload_file, get_upload_path
from handler.xjxc_parse_result import XjxcParseResult
from config.common import XJXC_TABLE_SEPARATOR_TITLE


# 解析出PDF中表格外头部的巡检巡查信息（报告编号、日期、标题等）
def parse_table_outer_info(page, position) -> Any | None:
    try:
        return page.get_text().split('\n')[position].strip()
    except IndexError:
        return None


def match_title(text: str) -> str | None:
    # match = re.search(r'' + title, text)
    # if match:
    #     return True
    # return False
    blocks = text.split('\n')
    for block in blocks:
        block = block.strip()
        if len(block) < 1:
            continue
        for separator in XJXC_TABLE_SEPARATOR_TITLE:
            if separator in block:
                return separator


def match_date(text: str) -> str | None:
    match = re.search(r'日期[:：]\s*\d{4}-\d{2}-\d{2}', text)
    if match:
        return match.group()
    return None


# 从字符串中解析日期
def parse_date_from_str(date_str, pattern) -> str:
    # # 正则表达式匹配 YYYY-MM-DD 格式的日期
    # date_pattern = r'\d{4}-\d{2}-\d{2}'
    # # 在字符串中查找日期
    # match = re.search(date_pattern, date_str)
    # if match:
    #     date_str = match.group()
    #     # 将匹配到的日期字符串解析为 datetime 对象
    #     # date_obj = datetime.strptime(date_str, '%Y-%m-%d')
    #     return date_str

    # 使用 dateutil 解析日期
    date_obj = parser.parse(date_str, fuzzy=True)
    return date_obj.strftime(pattern)


# 计算图像的哈希值
def calc_hash(image_bytes):
    # 创建 BytesIO 对象
    image_buffer = io.BytesIO(image_bytes)
    # 使用 PIL 打开图像
    image = Image.open(image_buffer)
    # 将图像转换为灰度图像
    image_gray = image.convert('L')
    # 计算平均哈希值
    hash_value = imagehash.average_hash(image_gray)
    return hash_value.__str__()


# 将PIL图像对象保存到字节流中
def convert_image_to_bytes(image, format='PNG'):
    buffered = io.BytesIO()
    image.save(buffered, format=format)
    # 重置buffer指针到开始位置
    buffered.seek(0)
    return buffered


# 记录巡检巡查结果
def save_xjxc_result(xjxc_results, xjxc_result, doc, file_name, inspect_date, start_page, end_page):
    image_path = get_upload_path(f'{file_name}-{inspect_date}-{start_page + 1}-{end_page}.png')
    save_pdf_table_image_to_oss(doc, image_path, start_page, end_page)
    xjxc_result.images = image_path
    xjxc_results.append(xjxc_result)


def save_pdf_table_image_to_oss(doc, image_path, start_page, end_page):
    """
       将PDF的多页保存成一张图片
       :param doc: PDF文件
       :param image_path: 图片相对路径
       :param start_page: 要渲染的页面起始页
       :param end_page: 要渲染的页面结束页
    """
    # 创建一个空白图片，用于存放所有页面
    width = int(doc[0].rect.width)
    height = sum(int(doc[page].rect.height) for page in range(start_page, end_page))
    combined_image = Image.new("RGB", (width, height), (255, 255, 255))

    # 存储当前图片的y坐标
    y_offset = 0
    for page_num in range(start_page, end_page):
        # 加载指定页码的页面
        page = doc.load_page(page_num)
        # 渲染页面为图片
        pix = page.get_pixmap()
        img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
        # 将页面图片粘贴到combined_image上
        combined_image.paste(img, (0, y_offset))
        # 更新y坐标
        y_offset += pix.height

    buffered = convert_image_to_bytes(combined_image)
    upload_file(image_path, buffered)


def create_xjxc_parse_result(title, inspect_date):
    return XjxcParseResult(project_name=title.replace('检查记录表', ''),
                           task_name=title.replace('表', ''), inspect_date=inspect_date)


def create_xjxc_parse_result_2(title, file_name, inspect_date):
    return XjxcParseResult(project_name=title.replace('检查记录表', ''),
                           task_name=file_name.replace('表', ''), inspect_date=inspect_date)


def get_file_name(pdf_path):
    file_path = pdf_path.split('/')
    return file_path[len(file_path) - 1].split('.')[0]


if __name__ == '__main__':
    print(parse_date_from_str('日期：2023-01-01', '%Y-%m-%d'))
